package com.zt.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.context.annotation.Configuration;

import java.util.Calendar;
import java.util.Map;

@Configuration
public class JwtToken {
    private static String str = "zt666";
	//-javaagent:D:\skywalking-agent\skywalking-agent.jar
	//-Dskywalking.agent.service_name=book8000
	//-Dskywalking.collector.backend_service=localhost:11800

    /**
     * 创建jwt
     *
     * @return
     */
    public static String createJetToken(Map<String, Object> claims) {

        String token = JWT.create()
                //添加载荷
                .withClaim("claims", claims)
                //添加过期时间
                .withExpiresAt(getCalendar().getTime())
                //指定算法 配置密码
                .sign(Algorithm.HMAC256(str));
        return token;
    }

    /**
     * 获取过期时间 System.currentTimeMillis(); 可能出现负数
     *
     * @return
     */
    public static Calendar getCalendar() {
        Calendar c = Calendar.getInstance();
        c.set(Calendar.SECOND, 60 * 60 * 24);
        return c;
    }

    public static Map<String, Object> resolveJwt(String headerToken) {
           //require申请一个JWT的验证器 通过build生成一个验证器
           JWTVerifier verifier = JWT.require(Algorithm.HMAC256(str)).build();
           //通过 verifier 去验证token 生成解析后的jwt对象
           DecodedJWT verify = verifier.verify(headerToken);
           Map<String, Object> claims = verify.getClaim("claims").asMap();
           return claims;

    }


    public static void main(String[] args) {
        resolveJwt("23");
    }
}
